local Mode = false
local id = "nightsight"
local s_util = require "libs/settingmanager"
local savedata


-- player.light = player.entity:AddLight()
-- player.light:SetFalloff(0.5)
-- player.light:SetIntensity(player.lightx or 1)
-- player.light:SetRadius(10^4)
-- player.light:SetColour(255/255, 225/255, 255/255)
-- player.light:Enable(true)

local function GetPv()
	return GLOBAL.ThePlayer and GLOBAL.ThePlayer.components.playervision
end

local function GetState()
	return GLOBAL.TheWorld and GLOBAL.TheWorld.state
end

local function TurnOff()
	if not Mode then return end
	local pv = GetPv()
	local wd = GetState()
	if pv and wd and not wd.isnight then
		pv:ForceNightVision(false)
		return true
	end
end
local function TurnOn()
	if not Mode then return end
	local pv = GetPv()
	local wd = GetState()
	if pv and wd and wd.isnight 
	 and not wd.isfullmoon -- 月圆难以提前预测
	then
		pv:ForceNightVision(true)
		return true
	end
end


local _lock
AddPlayerActivatedFunc(function(player)
	if not _lock then
		_lock = true
		local w_util = require "libs/worldutil"
		savedata = s_util:GetSettingLine(id)
		Mode = savedata.mode == true
		w_util:SetBindState("startday",function() GLOBAL.TheGlobalInstance:DoTaskInTime(5, TurnOff) end)
		w_util:SetBindState("startnight",function()
			GLOBAL.TheGlobalInstance:DoTaskInTime(0.1, function()
				if TurnOn() then
					TIP("提示", "blue", "夜晚到来, 请准备光源")
				end
			end)
		end)
	end
	player:DoTaskInTime(3, TurnOn)
end)

local function Fn()
	Mode = Mode == true
	Mode = not Mode
	savedata.mode = Mode
	s_util:SaveSettingLine(id, savedata)
	
	local wd = GetState()
	if Mode then
		TurnOn()
		if wd then
			TIP("开启", "green", wd.isnight and "智能夜视已开启" or "智能夜视已开启, 夜晚将会自动启用")
		end
	else
		local pv = GetPv()
		if pv then
			pv:ForceNightVision(false)
		end
		TIP("关闭", "red", "夜视已关闭")
	end
end




if GetModConfigData("cheat_nightversion") == "biubiu" then
	DEAR_BTNS:AddDearBtn(GLOBAL.GetInventoryItemAtlas("wx78module_nightvision.tex"), "wx78module_nightvision.tex", "夜视", "现在夜视状态会保存了", false, Fn)
end

AddBindBtn("cheat_nightversion", Fn)